<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\SkuMaterial as SkuMaterialService;
use app\common\service\Material as MaterialService;
use app\common\service\Sku as SkuService;

class Sku extends Admin
{
    protected $hisiModel = 'Sku';//模型名称[通用添加、修改专用]
    protected $hisiValidate = 'Sku';
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名

    public function initialize() {
    	parent::initialize();
    }

    public function index()
    {
    	$factoryKV = getFactoryKV(true);
    	if ($this->request->isAjax()) {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$keyword    = $this->request->param('keyword/s');

    		if ($keyword) {
    			$where[] = ['sku', 'like', "%{$keyword}%"];
    		}

    		$order = 'id desc';
    		$data['data'] = db('sku')->where($where)->page($page)->limit($limit)->order($order)->select();
    		foreach ($data['data'] as $k => $v) {
    			$tags = db('tags')->where('id', 'in', db('sku_tags')->where('sku_id', $v['id'])->column('tags_id'))->column('name');
    			if ($v['factory_id']) {
    				$tags[] = '复色('.$factoryKV[$v['factory_id']].')';
    			}
    			$data['data'][$k]['tags'] = implode(',', $tags);
    		}

    		$data['count'] = db('sku')->where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}

    	$assign = [];
    	return $this->assign($assign)->fetch();
    }

    /**
     * 添加
     */
    public function add() {
    	$formData = [];
    	$skuMaterialService = new SkuMaterialService();

    	if ($this->request->isAjax()) {

    		try {
    			db()->startTrans();
    			$customerDosageArr = $this->request->param('customer_dosage/a', []);
    			$materialDosageArr = $this->request->param('material_dosage/a', []);
    			$accurateDosageArr = $this->request->param('accurate_dosage/a', []);
    			$customerWeightPageArr = $this->request->param('customer_weight_page/a', []);
    			$diffLengthArr = $this->request->param('diff_length/a', []);
    			if (empty($customerDosageArr) || empty($materialDosageArr)) {
    				throw new \Exception('未关联材料');
    			}

    			$skuData = [];
    			$skuData['sku'] = $this->request->param('sku/s', '');
    			if(db('sku')->where('sku', $skuData['sku'])->value('id', 0)) {
    				throw new \Exception('该SKU已存在');
    			}

    			$skuData['pic'] = $this->request->param('pic/s', '');
    			$skuData['price'] = $this->request->param('price/f', 0);
    			$skuData['cost'] = $this->request->param('cost/f', 0);
				$skuData['cost_little'] = $this->request->param('cost_little/f', 0);
				$skuData['cost_scale'] = $this->request->param('cost_scale/f', 0);
				$skuData['outsource_price'] = $this->request->param('outsource_price/f', 0);
    			$skuData['chewei_price'] = $this->request->param('chewei_price/f', 0);
    			$skuData['sixian_price'] = $this->request->param('sixian_price/f', 0);
    			$skuData['zhuanji_price'] = $this->request->param('zhuanji_price/f', 0);
    			$skuData['zj_name'] = $this->request->param('zj_name/s', '');
    			$skuData['zj_count'] = $this->request->param('zj_count/d', 0);
    			$skuData['zj_unitprice'] = $this->request->param('zj_unitprice/f', 0);
    			$skuData['zj_price'] = $this->request->param('zj_price/f', 0);
    			$skuData['special_process_a_name'] = $this->request->param('special_process_a_name/s', '');
    			$skuData['special_process_a_count'] = $this->request->param('special_process_a_count/d', 0);
    			$skuData['special_process_a_unitprice'] = $this->request->param('special_process_a_unitprice/f', 0);
    			$skuData['special_process_a_price'] = $this->request->param('special_process_a_price/f', 0);
    			$skuData['special_process_b_name'] = $this->request->param('special_process_b_name/s', '');
    			$skuData['special_process_b_count'] = $this->request->param('special_process_b_count/d', 0);
    			$skuData['special_process_b_unitprice'] = $this->request->param('special_process_b_unitprice/f', 0);
    			$skuData['special_process_b_price'] = $this->request->param('special_process_b_price/f', 0);
    			$skuData['factory_id'] = $this->request->param('factory_id/d', 0);
    			$skuData['process'] = $this->request->param('process/s', '');
    			$skuData['cutting_requirements'] = $this->request->param('cutting_requirements/s', '');
    			$skuData['workshop_requirements'] = $this->request->param('workshop_requirements/s', '');
    			$skuData['tail_requirements'] = $this->request->param('tail_requirements/s', '');

    			$sizenameData = $this->request->param('sizename/a', []);
    			$measurementData = $this->request->param('measurement/a', []);
    			$partData = $this->request->param('part/a', []);
    			$sizeData = $this->request->param('size/a', []);

    			$skuData['ps_part'] = json_encode($partData);
    			$skuData['ps_measurement'] = json_encode($measurementData);

    			if (count(array_filter($sizenameData)) != count(array_unique(array_filter($sizenameData)))) {
    				throw new \Exception('尺码设置异常');
    			}

    			if (count(array_filter($partData)) != count(array_unique(array_filter($partData)))) {
    				throw new \Exception('部位设置异常');
    			}

    			$psSizenameData = [];
    			$psSizeData = [];
    			foreach ($sizenameData as $k => $v) {
    				if ($v != '') {
    					$items = arrayGet($sizeData, $k, []);
    					foreach ($items as $sv) {
    						if ($sv == '') throw new \Exception("尺码 {$v} 列有数据未填写");
    					}

    					$psSizenameData[] = $v;
    					$psSizeData[] = $items;
    				} else {
    					unset($sizenameData[$k]);
    					unset($sizeData[$k]);
    				}
    			}
    			$skuData['ps_size_name'] = json_encode($psSizenameData);
    			$skuData['ps_size'] = json_encode($psSizeData);

    			$skuData['style_name'] = $this->request->param('style_name/s', '');
    			$skuData['sku_type'] = $this->request->param('sku_type/s', '');
    			$skuData['caichuang_position'] = $this->request->param('caichuang_position/d', '0');
    			$skuData['off_pressing_level'] = $this->request->param('off_pressing_level/d', '0');
    			$skuData['special_process_a_level'] = $this->request->param('special_process_a_level/d', '0');
    			$skuData['special_process_b_level'] = $this->request->param('special_process_b_level/d', '0');
    			$skuData['zj_level'] = $this->request->param('zj_level/d', '0');

    			$id = db('sku')->insertGetId($skuData);

    			// 处理产品材料
    			foreach ($customerDosageArr as $materialId => $val) {
    				$upData = [
    					'material_dosage' => arrayGet($materialDosageArr, $materialId, 0),
    					'customer_dosage' => arrayGet($customerDosageArr, $materialId, 0),
    					'accurate_dosage' => arrayGet($accurateDosageArr, $materialId, 0),
    					'update_time' => time(),
    				];
    				$upData['sku_id'] = $id;
    				$upData['material_id'] = $materialId;
    				$upData['create_time'] = time();
    				db('sku_material')->insert($upData);

    				// 更新客户纸筒重量和空差
    				$upMaterialData = [];
    				$customerWeightPage = arrayGet($customerWeightPageArr, $materialId, 0);
    				$diffLength = arrayGet($diffLengthArr, $materialId, 0);
    				if ($customerWeightPage > 0) $upMaterialData['customer_weight_page'] = $customerWeightPage;
    				if ($diffLength > 0) $upMaterialData['diff_length'] = $customerWeightPage;
    				if ($upMaterialData) {
    					db('material')->where('id', $materialId)->update($upMaterialData);
    				}
    			}

    			db()->commit();
    			(new SkuService())->updatePicCache($skuData['sku']);

    			return $this->Json(1);
    		} catch (\Exception $e) {
    			db()->rollback();
    			return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    		}
    	}

    	$assign = [
    		'formData' => $formData,
    		'factoryKV' => [''=>'请选择'] + getFactoryKV(true),
    		'smList' => [],
    		'sizeNameList' => [''=>'请选择'] + getSizeKV(),
    		'partList' => [''=>'请选择'] + getPartKV(),
            'partListAll' => db('part')->select(),
    		'sizenameArr' => [],
    		'partArr' => [],
    		'measurementArr' => [],
    		'sizeArr' => [],
    		'processLevel' => config('mimo.process_level'),
    		'caichuangPosition' => config('mimo.caichuang_position'),
    	];

    	$template = $this->request->param('template', 'form');
    	return $this->assign($assign)->fetch($template);
    }

    /**
     * 添加
     */
    public function addv2()
    {
        $formData = [];
        $skuMaterialService = new SkuMaterialService();
        if ($this->request->isAjax()) {
            try {
                db()->startTrans();
                $customerDosageArr = $this->request->param('customer_dosage/a', []);
                $materialDosageArr = $this->request->param('material_dosage/a', []);
                $accurateDosageArr = $this->request->param('accurate_dosage/a', []);
                $customerWeightPageArr = $this->request->param('customer_weight_page/a', []);
                $diffLengthArr = $this->request->param('diff_length/a', []);
                if (empty($customerDosageArr) || empty($materialDosageArr)) {
                    throw new \Exception('未关联材料');
                }

                $skuData = [];
                $skuData['sku'] = $this->request->param('sku/s', '');
                if (db('sku')->where('sku', $skuData['sku'])->value('id', 0)) {
                    throw new \Exception('该SKU已存在');
                }
                $pic_url = trim($this->request->param('pic_url/s', ''));
                $skuData['pic'] = $this->request->param('pic/s', '');
                $skuData['ori_pic'] = $skuData['pic'];
                if ($pic_url != '') {
                    $skuData['ori_pic'] = $skuData['pic'] = $pic_url;
                }
                $skuData['ori_pic'] = $skuData['pic'] = htmlspecialchars_decode($skuData['ori_pic']);
                $skuData['price'] = $this->request->param('price/f', 0);
                $skuData['cost_profit'] = $this->request->param('cost_profit/f', 0);
                $skuData['cost'] = $this->request->param('cost/f', 0);
                $skuData['cost_little'] = $this->request->param('cost_little/f', 0);
                $skuData['cost_scale'] = $this->request->param('cost_scale/f', 0);
                $skuData['outsource_price'] = $this->request->param('outsource_price/f', 0);
                $skuData['chewei_price'] = $this->request->param('chewei_price/f', 0);
                $skuData['sixian_price'] = $this->request->param('sixian_price/f', 0);
                $skuData['zhuanji_price'] = $this->request->param('zhuanji_price/f', 0);
                $skuData['zj_name'] = $this->request->param('zj_name/s', '');
                $skuData['zj_count'] = $this->request->param('zj_count/d', 0);
                $skuData['zj_unitprice'] = $this->request->param('zj_unitprice/f', 0);
                $skuData['zj_price'] = $this->request->param('zj_price/f', 0);
                $skuData['special_process_a_name'] = $this->request->param('special_process_a_name/s', '');
                $skuData['special_process_a_count'] = $this->request->param('special_process_a_count/d', 0);
                $skuData['special_process_a_unitprice'] = $this->request->param('special_process_a_unitprice/f', 0);
                $skuData['special_process_a_price'] = $this->request->param('special_process_a_price/f', 0);
                $skuData['special_process_b_name'] = $this->request->param('special_process_b_name/s', '');
                $skuData['special_process_b_count'] = $this->request->param('special_process_b_count/d', 0);
                $skuData['special_process_b_unitprice'] = $this->request->param('special_process_b_unitprice/f', 0);
                $skuData['special_process_b_price'] = $this->request->param('special_process_b_price/f', 0);
                $skuData['factory_id'] = $this->request->param('factory_id/d', 0);
                $skuData['special_process_factory_name'] = $this->request->param('special_process_factory_name/s', '');
                $skuData['process'] = $this->request->param('process/s', '');
                $skuData['cutting_requirements'] = $this->request->param('cutting_requirements/s', '');
                $skuData['workshop_requirements'] = $this->request->param('workshop_requirements/s', '');
                $skuData['tail_requirements'] = $this->request->param('tail_requirements/s', '');

                $sizenameData = $this->request->param('sizename/a', []);
                $measurementData = $this->request->param('measurement/a', []);
                $partData = $this->request->param('part/a', []);
                $sizeData = $this->request->param('size/a', []);
                $sizeTiaoData = $this->request->param('size_tiao/a', []);

                $skuData['ps_part'] = json_encode($partData);
                $skuData['ps_measurement'] = json_encode($measurementData);
                $skuData['ps_size_tiao'] = json_encode($sizeTiaoData);

                if (count(array_filter($sizenameData)) != count(array_unique(array_filter($sizenameData)))) {
                    throw new \Exception('尺码设置异常');
                }

                if (count(array_filter($partData)) != count(array_unique(array_filter($partData)))) {
                    throw new \Exception('部位设置异常');
                }

                $psSizenameData = [];
                $psSizeData = [];
                foreach ($sizenameData as $k => $v) {
                    if ($v != '') {
                        $items = arrayGet($sizeData, $k, []);
                        foreach ($items as $sv) {
                            if ($sv == '') throw new \Exception("尺码 {$v} 列有数据未填写");
                        }

                        $psSizenameData[] = $v;
                        $psSizeData[] = $items;
                    } else {
                        unset($sizenameData[$k]);
                        unset($sizeData[$k]);
                    }
                }
                $skuData['ps_size_name'] = json_encode($psSizenameData);
                $skuData['ps_size'] = json_encode($psSizeData);

                $skuData['style_name'] = $this->request->param('style_name/s', '');
                $skuData['sku_type'] = $this->request->param('sku_type/s', '');
                $skuData['caichuang_position'] = $this->request->param('caichuang_position/d', '0');
                $skuData['off_pressing_level'] = $this->request->param('off_pressing_level/d', '0');
                $skuData['special_process_a_level'] = $this->request->param('special_process_a_level/d', '0');
                $skuData['special_process_b_level'] = $this->request->param('special_process_b_level/d', '0');
                $skuData['zj_level'] = $this->request->param('zj_level/d', '0');
                $skuData['create_time'] = time();
                $skuData['update_time'] = time();

                $id = db('sku')->insertGetId($skuData);

                // 处理产品材料
                foreach ($customerDosageArr as $materialId => $val) {
                    $upData = [
                        'material_dosage' => arrayGet($materialDosageArr, $materialId, 0),
                        'customer_dosage' => arrayGet($customerDosageArr, $materialId, 0),
                        'accurate_dosage' => arrayGet($accurateDosageArr, $materialId, 0),
                        'update_time' => time(),
                    ];
                    $upData['sku_id'] = $id;
                    $upData['material_id'] = $materialId;
                    $upData['create_time'] = time();
                    $temp = db('sku_material')->insert($upData);

                    // 更新客户纸筒重量和空差
                    $upMaterialData = [];
                    $customerWeightPage = arrayGet($customerWeightPageArr, $materialId, 0);
                    $diffLength = arrayGet($diffLengthArr, $materialId, 0);
                    if ($customerWeightPage > 0) $upMaterialData['customer_weight_page'] = $customerWeightPage;
                    if ($diffLength > 0) $upMaterialData['diff_length'] = $customerWeightPage;
                    if ($upMaterialData) {
                    	db('material')->where('id', $materialId)->update($upMaterialData);
                    }
                }

                db()->commit();
                (new SkuService())->updatePicCache($skuData['sku']);

                return $this->Json(1);
            } catch (\Exception $e) {
                db()->rollback();
                return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
            }
        }
        $assign = [
            'formData' => $formData,
            'factoryKV' => ['' => '请选择'] + getFactoryKV(true),
            'smList' => [],
            'sizeNameList' => ['' => '请选择'] + getSizeKV(),
            'partList' => ['' => '请选择'] + getPartKV(),
            'partListAll' => db('part')->select(),
            'sizenameArr' => [],
            'partArr' => [],
            'measurementArr' => [],
            'sizeArr' => [],
            'processLevel' => config('mimo.process_level'),
            'caichuangPosition' => config('mimo.caichuang_position'),
            'xm_select_data' => $this->_get_xm_select_data(),
        ];
        $template = $this->request->param('template', 'form');
        return $this->assign($assign)->fetch($template);
    }

    private function _get_xm_select_data()
    {
        $res = [];
        $list = db('size')->order('num asc,id asc')->select();
        foreach ($list as $k => $v) {
            $res[] = [
                'name' => $v['name'],
                'value' => $v['id'],
                'data-option' => $v['num'],
                'data-order' => $k,
            ];
        }
        return $res;
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $id = $this->request->param('id/d', 0);
        $formData = db('sku')->where('id', $id)->find();
        $skuMaterialService = new SkuMaterialService();
        $materialService = new MaterialService();

        if ($this->request->isAjax()) {

            try {
                db()->startTrans();
                $customerDosageArr = $this->request->param('customer_dosage/a', []);
                $materialDosageArr = $this->request->param('material_dosage/a', []);
                $accurateDosageArr = $this->request->param('accurate_dosage/a', []);
                $tube_weight = $this->request->param('tube_weight/a', []);
                $diff_meters = $this->request->param('diff_meters/a', []);
                if (empty($customerDosageArr) || empty($materialDosageArr)) {
                    throw new \Exception('未关联材料');
                }

                $skuData = [];$changesku='';
                $skuData['sku'] = $this->request->param('sku/s', '');
                if($skuData['sku']!=$formData['sku']){
                    if(db('sku')->where('sku', $skuData['sku'])->value('id', 0)) {
                        throw new \Exception('该SKU已存在');
                    }
                    $hasSkuOrder=db('order')->where('sku', $formData['sku'])->where('status', '<>', 99)->find();
                    if($hasSkuOrder){//原来sku存在订单，则不更改sku
                        unset($skuData['sku']);$changesku=',原sku存在订单，sku未做调整';
                    }
                }

                $skuData['pic'] = $this->request->param('pic/s', '');
                $skuData['ori_pic'] = $this->request->param('pic/s', '');
                $pic_url = trim($this->request->param('pic_url/s', ''));
                if ($pic_url != '') {
                    $skuData['ori_pic'] = $skuData['pic'] = $pic_url;
                }
                $skuData['ori_pic'] = $skuData['pic'] = htmlspecialchars_decode($skuData['ori_pic']);
                $skuData['price'] = $this->request->param('price/f', 0);
                $skuData['cost'] = $this->request->param('cost/f', 0);
                $skuData['cost_little'] = $this->request->param('cost_little/f', 0);
                $skuData['cost_scale'] = $this->request->param('cost_scale/f', 0);
                $skuData['outsource_price'] = $this->request->param('outsource_price/f', 0);
                $skuData['chewei_price'] = $this->request->param('chewei_price/f', 0);
                $skuData['sixian_price'] = $this->request->param('sixian_price/f', 0);
                $skuData['zhuanji_price'] = $this->request->param('zhuanji_price/f', 0);
                $skuData['zj_name'] = $this->request->param('zj_name/s', '');
                $skuData['zj_count'] = $this->request->param('zj_count/d', 0);
                $skuData['zj_unitprice'] = $this->request->param('zj_unitprice/f', 0);
                $skuData['zj_price'] = $this->request->param('zj_price/f', 0);
                $skuData['special_process_a_name'] = $this->request->param('special_process_a_name/s', '');
                $skuData['special_process_a_count'] = $this->request->param('special_process_a_count/d', 0);
                $skuData['special_process_a_unitprice'] = $this->request->param('special_process_a_unitprice/f', 0);
                $skuData['special_process_a_price'] = $this->request->param('special_process_a_price/f', 0);
                $skuData['special_process_b_name'] = $this->request->param('special_process_b_name/s', '');
                $skuData['special_process_b_count'] = $this->request->param('special_process_b_count/d', 0);
                $skuData['special_process_b_unitprice'] = $this->request->param('special_process_b_unitprice/f', 0);
                $skuData['special_process_b_price'] = $this->request->param('special_process_b_price/f', 0);
                $skuData['factory_id'] = $this->request->param('factory_id/d', 0);
                $skuData['special_process_factory_name'] = $this->request->param('special_process_factory_name/s', '');
                $skuData['process'] = $this->request->param('process/s', '');
                $skuData['cutting_requirements'] = $this->request->param('cutting_requirements/s', '');
                $skuData['workshop_requirements'] = $this->request->param('workshop_requirements/s', '');
                $skuData['tail_requirements'] = $this->request->param('tail_requirements/s', '');
                $skuData['fabrics_process_addr'] = $this->request->param('fabrics_process_addr/s', 0);//面辅可加工地区 0均可加工，1只广州可加工
                $skuData['fabrics_process_complexity'] = $this->request->param('fabrics_process_complexity/s', 1);//面辅加工难度 自动分单辅助信息
                $sizenameData = $this->request->param('sizename/a', []);
                $measurementData = $this->request->param('measurement/a', []);
                $partData = $this->request->param('part/a', []);
                $sizeData = $this->request->param('size/a', []);
                $sizeTiaoData = $this->request->param('size_tiao/a', []);

                $skuData['ps_part'] = json_encode($partData);
                $skuData['ps_measurement'] = json_encode($measurementData);
                $skuData['ps_size_tiao'] = json_encode($sizeTiaoData);

                $skuData['style_name'] = $this->request->param('style_name/s', '');
                $skuData['sku_type'] = $this->request->param('sku_type/s', '');
                $skuData['caichuang_position'] = $this->request->param('caichuang_position/d', '0');
                $skuData['off_pressing_level'] = $this->request->param('off_pressing_level/d', '0');
                $skuData['special_process_a_level'] = $this->request->param('special_process_a_level/d', '0');
                $skuData['special_process_b_level'] = $this->request->param('special_process_b_level/d', '0');
                $skuData['zj_level'] = $this->request->param('zj_level/d', '0');

                if (count(array_filter($sizenameData)) != count(array_unique(array_filter($sizenameData)))) {
                    throw new \Exception('尺码设置异常');
                }

                if (count(array_filter($partData)) != count(array_unique(array_filter($partData)))) {
                    throw new \Exception('部位设置异常');
                }

                $psSizenameData = [];
                $psSizeData = [];
                foreach ($sizenameData as $k => $v) {
                    if ($v != '') {
                        $items = arrayGet($sizeData, $k, []);
                        foreach ($items as $sv) {
                            if ($sv == '') throw new \Exception("尺码 {$v} 列有数据未填写");
                        }

                        $psSizenameData[] = $v;
                        $psSizeData[] = $items;
                    } else {
                        unset($sizenameData[$k]);
                        unset($sizeData[$k]);
                    }
                }
                $skuData['ps_size_name'] = json_encode($psSizenameData);
                $skuData['ps_size'] = json_encode($psSizeData);

                db('sku')->where('id', $id)->update($skuData);
                $sku = db('sku')->where('id', $id)->value('sku');

                // 处理产品材料
                db('sku_material')->where('sku_id', $id)->where('material_id', 'not in', array_keys($customerDosageArr))->delete();
                foreach ($customerDosageArr as $materialId => $val) {
                    $skuMaterialInfo = db('sku_material')->where('sku_id', $id)->where('material_id', $materialId)->field('mid,material_dosage')->findOrEmpty();
                    $upData = [
                        'material_dosage' => arrayGet($materialDosageArr, $materialId, 0),
                        'customer_dosage' => arrayGet($customerDosageArr, $materialId, 0),
                        'accurate_dosage' => arrayGet($accurateDosageArr, $materialId, 0),
                        'update_time' => time(),
                    ];
                    if ($skuMaterialInfo) {
                        db('sku_material')->where('sku_id', $id)->where('material_id', $materialId)->update($upData);
                    } else {
                        $upData['sku_id'] = $id;
                        $upData['material_id'] = $materialId;
                        $upData['create_time'] = time();
                        db('sku_material')->insert($upData);
                    }

                    // 米莫用量 同步更新到 订单的米莫用量
                    $upOrderList = db('order')->where('sku', $sku)->where('status', 'in', [0, 1])->column('client_ordernum', 'id');
                    $upOrderMaterialList = db('order_material')->where('material_id', $materialId)->where('order_id', 'in', array_keys($upOrderList))->column('material_dosage,order_id,client_ordernum,material_id', 'mid');
                    foreach ($upOrderMaterialList as $mid => $v) {
                        if ($v['material_dosage'] != $upData['material_dosage']) {
                            db('order_material')->where('mid', $mid)->update(['material_dosage' => $upData['material_dosage']]);
                            $this->addOrderLog($v['order_id'], $v['client_ordernum'], "产品编辑，修改物料[" . $materialService->getMaterialName($v['material_id']) . "]的" . config('base.company_short_name') . "用量为 {$upData['material_dosage']}");
                        }
                    }
                    $upMaterialData = ['id' => $materialId, 'customer_weight_page' => $tube_weight[$materialId], 'diff_length' => $diff_meters[$materialId]];
                    db('material')->where('id', $materialId)->update($upMaterialData);
                }

                db()->commit();

                (new SkuService())->updatePicCache($formData['sku']);
                $msg='保存成功'.$changesku;
                return $this->Json(1,$msg);
            } catch (\Exception $e) {
                db()->rollback();
                return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
            }
        }

        $psSizeArr = [];
        $psSize = json_decode($formData['ps_size'], true);
        $formData['outsource_per'] = $formData['cost_little'] != 0 ? round($formData['outsource_price'] / $formData['cost_little'], 2) : 0;
        $formData['outsource_perb'] = $formData['cost'] != 0 ? round($formData['outsource_price'] / $formData['cost'] * 100, 3) . "%" : '0%';
        foreach ($psSize as $k => $v) {
            $psSizeArr[] = array_values($v);
        }
        $formData['is_new'] = (db('order')->where(['sku' => $formData['sku']])->count() < 2) ? '是' : '否'; // 是否新款
        $formData['a_material_name'] = ($formData['a_material_id'] ? $materialService->getMaterialName($formData['a_material_id']) : ''); // 面料种类
        $assign = [
            'formData' => $formData,
            'factoryKV' => ['' => '请选择'] + getFactoryKV(true),
            'smList' => $skuMaterialService->getListBySkuId($id),
            'sizeNameList' => ['' => '请选择'] + getSizeKV(),
            'partList' => ['' => '请选择'] + getPartKV(),
            'partListAll' => db('part')->select(),
            'sizenameArr' => json_decode($formData['ps_size_name'], true) ? array_values(json_decode($formData['ps_size_name'], true)) : [],
            'partArr' => json_decode($formData['ps_part'], true) ? array_values(json_decode($formData['ps_part'], true)) : [],
            'measurementArr' => json_decode($formData['ps_measurement'], true) ? array_values(json_decode($formData['ps_measurement'], true)) : [],
            'sizeTiaoArr' => json_decode($formData['ps_size_tiao'], true) ? array_values(json_decode($formData['ps_size_tiao'], true)) : [],
            'sizeArr' => $psSizeArr,
            'processLevel' => config('mimo.process_level'),
            'caichuangPosition' => config('mimo.caichuang_position'),
            'xm_select_data' => $this->_get_xm_select_data(),
        ];

        $template = $this->request->param('template', 'form');
        return $this->assign($assign)->fetch($template);
    }

    /**
     * 删除
     */
    public function del() {
		$id = $this->request->param('id/a', []);

		if(db('order')->where('sku', 'in', db('sku')->where('id', 'in', $id)->column('sku'))->count()) {
			$this->error('已有订单在使用该产品，无法删除');
		}

		try {
			db()->startTrans();
			db('sku')->where('id', 'in', $id)->delete();
			db('sku_component')->where('sku_id', 'in', $id)->delete();
			db('sku_material')->where('sku_id', 'in', $id)->delete();
			db('sku_tags')->where('sku_id', 'in', $id)->delete();

			db()->commit();
			return $this->Json(1);
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
    }

    /**
     * 工价列表
     *
     * @author King
     * @date 2020年9月8日
     *
     * @return json
     */
    public function wages()
    {
    	if ($this->request->isAjax()|| $this->request->param('export/d', 0)) {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$keyword    = $this->request->param('keyword/s');
			$export     = $this->request->param('export/d', 0);
			if ($export) {
				set_time_limit(0);
				ini_set('memory_limit', '1024M');
				$page = 1;
				$limit = 99999;
			}
    		if ($keyword) {
    			$where[] = ['sku', 'like', "%{$keyword}%"];
    		}

    		$order = 'id desc';
    		$data['data'] = db('sku')->where($where)->page($page)->limit($limit)->order($order)->select();
    		$data['count'] = db('sku')->where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
			// 导出
			if ($export) {
				$this->_exportXls('工价表-' .date('YmdHis'), $data['data']);
				exit;
			}
    		return json($data);
    	}

    	$assign = [];
    	return $this->assign($assign)->fetch();
    }

		/**
	 * 工价表导出
	 *
	 * @author King
	 * @date 2021年6月28日
	 *
	 */
	private function _exportXls($title, &$list) {
		$params = [];
		$data = [];
		foreach ($list as $k => $v) {
//			 $picData = '';
//			$pic = arrayGet($v['sInfo'], 'pic', '');
//			if ($pic != '' && env('env')=='production' && stripos($pic, IMG_URL) !== false) {
//				$cellVal = env('root_path') . 'public/' . str_replace(IMG_URL, "", $pic);
//				$picData = ['pic' => $cellVal];
//			}
			$data[] = [
				$v['id'],
				$v['sku'],
				$v['chewei_price'],
				$v['sixian_price'],
				$v['zhuanji_price'],
				$v['process'],
				date('Y-m-d H:i:s', $v['update_time']),
			];
		}

		$params['file'] = $title;
		$params['sheet'] = [
			[
				'head' => ['编号','sku','车位价','打边价','冚车价','工艺','更新时间'], // 表头
				'data' => $data,
			],
		];
		unset($list);
		plugins_run('excel/excel/export', $params);
	}

    /**
     * 产品打印--与edit方法一样逻辑显示数据
     * @date 2021/12/16
     * @author zhuguosen 905502314@qq.com
     */
	public function print(){
        $id = $this->request->param('id/d', 0);
        $formData = db('sku')->where('id', $id)->find();
        $skuMaterialService = new SkuMaterialService();
        $materialService = new MaterialService();
        $psSizeArr = [];
        $psSize = json_decode($formData['ps_size'], true);
        $formData['outsource_per'] = $formData['cost_little'] != 0 ? round($formData['outsource_price'] / $formData['cost_little'], 2) : 0;
        $formData['outsource_perb'] = $formData['cost'] != 0 ? round($formData['outsource_price'] / $formData['cost'] * 100, 3) . "%" : '0%';
        foreach ($psSize as $k => $v) {
            $psSizeArr[] = array_values($v);
        }
        $formData['is_new'] = (db('order')->where(['sku' => $formData['sku']])->count() < 2) ? '是' : '否'; // 是否新款
        $formData['a_material_name'] = ($formData['a_material_id'] ? $materialService->getMaterialName($formData['a_material_id']) : ''); // 面料种类
        $assign = [
            'formData' => $formData,
            'factoryKV' => ['' => '请选择'] + getFactoryKV(true),
            'smList' => $skuMaterialService->getListBySkuId($id),
            'sizeNameList' => ['' => '请选择'] + getSizeKV(),
            'partList' => ['' => '请选择'] + getPartKV(),
            'partListAll' => db('part')->select(),
            'sizenameArr' => json_decode($formData['ps_size_name'], true) ? array_values(json_decode($formData['ps_size_name'], true)) : [],
            'partArr' => json_decode($formData['ps_part'], true) ? array_values(json_decode($formData['ps_part'], true)) : [],
            'measurementArr' => json_decode($formData['ps_measurement'], true) ? array_values(json_decode($formData['ps_measurement'], true)) : [],
            'sizeTiaoArr' => json_decode($formData['ps_size_tiao'], true) ? array_values(json_decode($formData['ps_size_tiao'], true)) : [],
            'sizeArr' => $psSizeArr,
            'processLevel' => config('mimo.process_level'),
            'caichuangPosition' => config('mimo.caichuang_position'),
        ];

        return $this->assign($assign)->fetch();
    }

    public function setimg()
    {
        if ($this->request->isAjax()) {
            $pic = $this->request->param('pic/s', '');
            $client_ordernum = trim($this->request->param('client_ordernum/s', ''));
            if ($pic == '' || $client_ordernum == '') {
                return $this->Json(0, '操作失败，');
            }
            $skuInfo = db('order o')
                ->field('o.id,o.client_ordernum,o.sku,s.pic')
                ->leftJoin('sku s', 'o.sku=s.sku')
                ->where([
                    ['o.client_ordernum', '=', $client_ordernum],
                ])
                ->find();
            db('sku')->where([
                ['sku', '=', $skuInfo['sku']],
            ])->update([
                'pic' => $pic,
                'ori_pic' => $pic,
                'pic_download_flag' => 1,
            ]);
            db('order_ext')->where([
                ['client_ordernum', '=', $skuInfo['client_ordernum']],
            ])->update([
//                'pic' => $pic,
//                'ori_pic' => $pic,
                'pic_download' => $pic,
            ]);
            if ($skuInfo['pic'] != '') {
                $msg = '';
                // 删除旧图片（http://www.020mimo.com/upload/202112/21/f5125cb6496bec04ac0b28e437eacf48.jpg）
                $oldPicPath = parse_url($skuInfo['pic'], PHP_URL_PATH); // /upload/202112/21/f5125cb6496bec04ac0b28e437eacf48.jpg
                $oldPic = env('root_path') . 'public' . $oldPicPath;
                if (file_exists($oldPic)) {
                    if (unlink($oldPic)) $msg = $msg . "，成功删除旧图片：" . $oldPicPath;
                    else $msg = $msg . "，删除旧图片失败：" . $oldPicPath;
                } else $msg = $msg . "，旧图片不存在：" . $oldPicPath;
            }
            return $this->Json(1, "操作成功", [$msg]);
        }
        $assign = [
            'formData' => [],
        ];
        return $this->assign($assign)->fetch();
    }
}